#include "Kernel.h"
#include "Hal/IHardware.h"
#include "Hal/x86/Hardware.h"
#include "Hal/x86/CPU.h"
#include "Hal/x86/IDT.h"
#include "Hal/x86/Timer.h"
#include "Scheduler/Scheduler.h"

using namespace x86;

uint16 divisor;
Result Timer::Initialize( uint16 hz )
{
	TIMER_TRACE( "Timer initializing...\n" );

	divisor = 1193180 / hz;

	IO_Out8( 0x43, 0x36 );
	IO_Out8( 0x40, (uint8)( divisor & 0xFF ) );
	IO_Out8( 0x40, (uint8)( ( divisor >> 8 ) & 0xFF ) );
	IO_Delay();

	IDT::RegisterHandler( INT_IRQ_0, &Handler );
	return RESULT_OK;
}


void Timer::Handler( ITaskContext * context )
{
	TIMER_TRACE( "Tick!\n" );

#if TRACE_HAL_DETAILED
	TRACE_CONTEXT( context );
#endif

	// send ack because we wont return
	IO_Out8( 0x20, 0x20 );
	IO_Delay();

	Scheduler::Schedule( context );
}

